#include "ProcessWidget.h"
#include <QPainter>
#include <QDebug>
#include <QFont>
#include <QFontMetrics>

ProcessWidget::ProcessWidget(QWidget *parent)
    : QWidget(parent)
    , m_currentStage(BlowingStart)
    , m_currentTime("05'31\"")
    , m_stageCompleted(9, false)
    , m_progressLineHeight(6)
    , m_stageMarkerRadius(9)
    , m_labelHeight(20)
{
    m_stageCompleted[SmeltingStart] = true;
    m_stageCompleted[AddScrapSteel] = true;
    m_stageCompleted[PourMoltenIron] = true;
    
    setupUI();
    setupConnections();
}

ProcessWidget::~ProcessWidget()
{
}

void ProcessWidget::setupUI()
{
    // 主布局
    m_mainLayout = new QHBoxLayout(this);
    m_mainLayout->setContentsMargins(6, 6, 6, 6);
    m_mainLayout->setSpacing(10);

    QVBoxLayout *leftLayout = new QVBoxLayout();
    leftLayout->setContentsMargins(0, 0, 0, 0);
    leftLayout->setSpacing(0);
    QHBoxLayout *hleftTitleLayout = new QHBoxLayout();
    hleftTitleLayout->setContentsMargins(0, 0, 0, 0);
    hleftTitleLayout->setSpacing(6);
    leftLayout->addLayout(hleftTitleLayout);
    leftLayout->addStretch();
    QLabel *markLabel = new QLabel();
    markLabel->setFixedSize(3, 18);
    markLabel->setStyleSheet("background-color: #02F9FDFF; border: none;");
    QLabel *titleLabel = new QLabel(QString("冶炼进程："));
    titleLabel->setProperty("label20", true);
    m_timeLabel = new QLabel(m_currentTime);
    m_timeLabel->setStyleSheet("color: #02F9FD; font-size: 20px; font-weight: bold;");
    hleftTitleLayout->addWidget(markLabel);
    hleftTitleLayout->addWidget(titleLabel);
    hleftTitleLayout->addWidget(m_timeLabel);
    m_mainLayout->addLayout(leftLayout);
    
    // 进度条组件
    m_progressWidget = new QWidget(this);
    m_mainLayout->addWidget(m_progressWidget, 1);
}

void ProcessWidget::setupConnections()
{
    // 暂时没有需要连接的信号槽
}

void ProcessWidget::setCurrentStage(ProcessStage stage)
{
    if (m_currentStage != stage) {
        m_currentStage = stage;
        update();
    }
}

ProcessWidget::ProcessStage ProcessWidget::getCurrentStage() const
{
    return m_currentStage;
}

void ProcessWidget::setCurrentTime(const QString &time)
{
    if (m_currentTime != time) {
        m_currentTime = time;
        m_timeLabel->setText("冶炼进程: " + m_currentTime);
    }
}

QString ProcessWidget::getCurrentTime() const
{
    return m_currentTime;
}

void ProcessWidget::setStageCompleted(ProcessStage stage, bool completed)
{
    if (stage >= 0 && stage < m_stageCompleted.size()) {
        m_stageCompleted[stage] = completed;
        update();
    }
}

bool ProcessWidget::isStageCompleted(ProcessStage stage) const
{
    if (stage >= 0 && stage < m_stageCompleted.size()) {
        return m_stageCompleted[stage];
    }
    return false;
}

void ProcessWidget::updateLayout()
{
    // 更新布局
    update();
}

QRect ProcessWidget::getStageRect(int stageIndex) const
{
    if (stageIndex < 0 || stageIndex >= 9) return QRect();
    
    int widgetWidth = m_progressWidget->width();
    int widgetHeight = m_progressWidget->height();
    
    int startX = 50;
    int endX = widgetWidth - 50;
    int lineY = widgetHeight / 2;
    
    int stageWidth = (endX - startX) / 8;
    int stageX = startX + stageIndex * stageWidth;
    
    return QRect(stageX - m_stageMarkerRadius, lineY - m_stageMarkerRadius,
                 m_stageMarkerRadius * 2, m_stageMarkerRadius * 2);
}

void ProcessWidget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    
    // 绘制背景渐变
    QLinearGradient gradient(0, 0, 0, height());
    gradient.setColorAt(0, QColor("#24598FFF"));
    gradient.setColorAt(1, QColor("#1A4D8200"));
    
    painter.setBrush(QBrush(gradient));
    painter.setPen(Qt::NoPen);
    painter.drawRoundedRect(rect(), 8, 8);
    
    // 绘制进度条组件
    if (m_progressWidget) {
        painter.save();
        painter.translate(m_progressWidget->pos());
        
        drawProgressLine(painter);
        drawStageMarkers(painter);
        drawStageLabels(painter);
        
        painter.restore();
    }
    
    QWidget::paintEvent(event);
}

void ProcessWidget::drawProgressLine(QPainter &painter)
{
    int widgetWidth = m_progressWidget->width();
    int widgetHeight = m_progressWidget->height();
    
    int startX = 50;
    int endX = widgetWidth - 50;
    int lineY = 12;
    
    int totalWidth = endX - startX;
    int stageWidth = totalWidth / 8;
    
    // 计算已完成阶段的进度
    int completedStages = 0;
    for (int i = 0; i < 9; ++i) {
        if (m_stageCompleted[i]) {
            completedStages++;
        }
    }
    
    // 绘制已走过的进度条（使用Progress bar.png）
    if (completedStages > 0) {
        QPixmap progressBarPixmap(":/img/images/Progress bar.png");
        if (!progressBarPixmap.isNull()) {
            int completedWidth = (completedStages * stageWidth);
            QRect completedRect(startX, lineY, completedWidth, m_progressLineHeight);
            painter.drawPixmap(completedRect, progressBarPixmap.scaled(completedRect.size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
        }
    }
    
    // 绘制未走过的进度条（填充#1A4677，描边#0D3969，1px）
    if (completedStages < 9) {
        int remainingStartX = startX + (completedStages * stageWidth);
        int remainingWidth = totalWidth - (completedStages * stageWidth);
        
        // 绘制填充
        painter.setPen(Qt::NoPen);
        painter.setBrush(QBrush(QColor("#1A4677")));
        QRect remainingRect(remainingStartX, lineY, remainingWidth, m_progressLineHeight);
        painter.drawRect(remainingRect);
        
        // 绘制描边
        painter.setPen(QPen(QColor("#0D3969"), 1));
        painter.setBrush(Qt::NoBrush);
        painter.drawRect(remainingRect);
    }
}

void ProcessWidget::drawStageMarkers(QPainter &painter)
{
    int widgetWidth = m_progressWidget->width();
    int widgetHeight = m_progressWidget->height();
    
    int startX = 50;
    int endX = widgetWidth - 50;
    int lineY = 12 + m_progressLineHeight / 2;
    
    int stageWidth = (endX - startX) / 8;
    
    for (int i = 0; i < 9; ++i) {
        int stageX = startX + i * stageWidth;
        
        QPixmap iconPixmap;
        QString iconPath;
        
        // 根据阶段状态选择图标
        if (m_stageCompleted[i]) {
            iconPath = ":/img/images/icon-Completed.png";
        } else if (i == static_cast<int>(m_currentStage)) {
            iconPath = ":/img/images/icon-In progress.png";
        } else {
            iconPath = ":/img/images/icon-Not started.png";
        }
        
        iconPixmap = QPixmap(iconPath);
        
        if (!iconPixmap.isNull()) {
            // 绘制状态图标
            QRect iconRect(stageX - m_stageMarkerRadius, lineY - m_stageMarkerRadius,
                          m_stageMarkerRadius * 2, m_stageMarkerRadius * 2);
            painter.drawPixmap(iconRect, iconPixmap.scaled(iconRect.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
        }
    }
}

void ProcessWidget::drawStageLabels(QPainter &painter)
{
    QStringList stageNames = {
        "冶炼开始", "加废钢", "兑铁水", "吹炼开始", "吹炼结束",
        "出钢", "溅渣", "出渣", "冶炼结束"
    };
    
    int widgetWidth = m_progressWidget->width();
    int widgetHeight = m_progressWidget->height();
    
    int startX = 50;
    int endX = widgetWidth - 50;
    int lineY = 6 + m_progressLineHeight;
    int labelY = lineY + m_stageMarkerRadius + 10;
    
    int stageWidth = (endX - startX) / 8;
    
    painter.setPen(QPen(QColor(255, 255, 255)));
    QFont font = painter.font();
    font.setPointSize(10);
    painter.setFont(font);
    
    for (int i = 0; i < 9; ++i) {
        int stageX = startX + i * stageWidth;
        
        QRect textRect(stageX - 30, labelY, 60, m_labelHeight);
        painter.drawText(textRect, Qt::AlignCenter, stageNames[i]);
    }
}

void ProcessWidget::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    updateLayout();
}
